﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////


#include "GnufDynamicZoneRefreshManager.h"
#include "GnufAssistantPanel.h"
#include "GnufButtonToolDefinition.h"
#include "GnufDynamicPanel.h"
#include "GnufDynamicZone.h"
#include "GnufMainToolbar.h"
#include "GnufToolDefinition.h"
#include "GnufUiDocUtils.h"
#include "IAction.h"
#include "IActionManager.h"
#include "IApplication.h"
#include "IGnufUIFactory.h"
#include "IEditMode.h"
#include "IUiDocument.h"
#include "IUiManager.h"
#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gnuf;
using namespace gcmp;
using namespace gfam;

GnufDynamicZoneRefreshManager::GnufDynamicZoneRefreshManager()
    : m_inSelectedEdition(false)
{
    m_event = NEW_AS_OWNER_PTR(RefreshDynamicZoneEvent);
    if (m_event)
    {
        m_event->setManager(this);
    }
}

GnufDynamicZoneRefreshManager::~GnufDynamicZoneRefreshManager()
{
}

void GnufDynamicZoneRefreshManager::SwitchTo(ETemporaryStatus status)
{
    switch (status)
    {
    case ETemporaryStatus::eCreation:
        SetGeneralEditionPanelVisibility(false);
        break;
    case  ETemporaryStatus::eGeneralEdition:
        SetGeneralEditionPanelVisibility(true);
        break;
    default:
        break;
    }
    UpdateDynamicPanels();

    if (m_actionQue.empty())
    {
        ResetDynamicPanels();
    }
}

void GnufDynamicZoneRefreshManager::SetGeneralEditionPanelVisibility(bool vis) const
{
    gnuf::AssistantPanel* pPanel = gnuf::AssistantPanel::get();
    DBG_WARN_AND_RETURN_VOID_UNLESS(pPanel, L"pPanel is nullptr", L"paramodel", L"2024-02-20");

    pPanel->setVisible(vis);
}

bool GnufDynamicZoneRefreshManager::InEditMode() const
{
    IUiDocument* pUiDoc = GnufUiDocUtils::GetCurrentUIDoc();
    if (pUiDoc)
    {
        IEditMode* pTopEditMode = IEditMode::GetTopActiveEditMode(pUiDoc->GetDbDocument());
        return pTopEditMode != nullptr;
    }
    return false;
}

void GnufDynamicZoneRefreshManager::postRefreshEvent(const IAction* pAction)
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(pAction, L"pAction是空指针", L"paramodel", L"2024-02-20");
    DBG_WARN_AND_RETURN_VOID_UNLESS(m_event, L"m_event是空指针", L"paramodel", L"2024-02-20");

    gcmp::OwnerPtr<RefreshDynamicZoneEvent> evt = NEW_AS_OWNER_PTR(RefreshDynamicZoneEvent, *m_event);
    DBG_WARN_AND_RETURN_VOID_UNLESS(evt, L"evt是空指针", L"paramodel", L"2024-02-20");
    evt->setCurrentCommandName(pAction->GetCommandId());

    DBG_WARN_AND_RETURN_VOID_UNLESS(gcmp::IApplication::Get(), L"IApplication::Get()是空指针", L"paramodel", L"2024-02-20");
    gcmp::IApplication::Get()->PostEvent(TransferOwnership(evt));
    m_actionQue.push(pAction->GetCommandId());
}

void GnufDynamicZoneRefreshManager::UpdateDynamicPanels() const
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(DynamicZone::get(), L"DynamicZone::get()是空指针", L"paramodel", L"2024-02-20");

    std::vector<int> panelIndex = { CREATION_TYPE_INDEX, CREATION_METHOD_INDEX, CREATION_CONSTRAINT_INDEX };
    FOR_EACH(index, panelIndex)
    {
        DynamicPanel* pPanel = DynamicZone::get()->getDynamicPanelAt(index);
        if (pPanel)
        {
            if(pPanel->userData().empty()) continue;

            DynamicPanelStatus status = pPanel->userData().cast<DynamicPanelStatus>();
            if (status == DynamicPanelStatus::eCreating)
                continue;
            else if (status == DynamicPanelStatus::eCreated)
                gnuf::DynamicZone::get()->clearDynamicPanelAt(index);
            else
                DBG_WARN(L"not possible situation", L"paramodel", L"2024-02-20");
        }
    }
}

bool GnufDynamicZoneRefreshManager::consistencyCheck(const std::wstring& cmd)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(cmd.compare(m_actionQue.front()) == 0,
        L"impossible situation", L"paramodel", L"2024-02-20");

    m_actionQue.pop();
    return true;
}

void GnufDynamicZoneRefreshManager::ResetDynamicPanels() const
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(DynamicZone::get(), L"DynamicZone::get()是空指针", L"paramodel", L"2024-02-20");

    std::vector<int> panelIndex = { CREATION_TYPE_INDEX, CREATION_METHOD_INDEX, CREATION_CONSTRAINT_INDEX };
    FOR_EACH(index, panelIndex)
    {
        DynamicPanel* pPanel = DynamicZone::get()->getDynamicPanelAt(index);

        // The creation type panel in edit mode is currently used by the client code to exhibit buttons that keep alive
        // until the edit mode finished, thus the creation type panel should keep creating status in edit mode.
        if (InEditMode() && index == CREATION_TYPE_INDEX) continue;

        if (pPanel) pPanel->setUserData(DynamicPanelStatus::eCreated);
    }
}

void RefreshDynamicZoneEvent::Emit()
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(m_manager, L"m_manager是空指针", L"paramodel", L"2024-02-20");
    DBG_WARN_AND_RETURN_VOID_UNLESS(ToolDefinitionManager::get() != nullptr, L"ToolDefinitionManager::get() is nullptr", L"paramodel", L"2024-02-20");
    DBG_WARN_AND_RETURN_VOID_UNLESS(MainToolbar::get() != nullptr, L"MainToolbar::get() is nullptr", L"paramodel", L"2024-02-20");
    DBG_WARN_AND_RETURN_VOID_UNLESS(DynamicZone::get() != nullptr, L"DynamicZone::get() is nullptr", L"paramodel", L"2024-02-20");

    bool bOk = m_manager->consistencyCheck(m_currentCommandName);
    DBG_WARN_AND_RETURN_VOID_UNLESS(bOk, L"consistency check failed", L"paramodel", L"2024-02-20");

    if (IAction* pTop = IActionManager::CurrentAction())
    {
        std::wstring commandId = pTop->GetCommandId();
        if (commandId.compare(m_generalEditCommandName) == 0)
        {
            m_manager->SwitchTo(ETemporaryStatus::eGeneralEdition);
            return;
        }
                    
        ToolDefinition* pDefinition = ToolDefinitionManager::get()->toolDefinitionBy(commandId);
        if (pDefinition != nullptr)
        {
            ButtonToolDefinition* pButtonDefinition = dynamic_cast<ButtonToolDefinition*>(pDefinition);
            if (pButtonDefinition != nullptr)
            {
                ButtonControl* pButtonControl = pButtonDefinition->buttonControl();
                DBG_WARN_AND_RETURN_VOID_UNLESS(pButtonControl != nullptr, L"pButtonControl is nullptr", L"paramodel", L"2024-02-20");

                if (pButtonControl->doesLocateAt(MainToolbar::get()->uniqueKey()))
                {
                    m_manager->SwitchTo(ETemporaryStatus::eCreation);
                }
                else if (DynamicPanel* pCreationPanel = DynamicZone::get()->getDynamicPanelAt(CREATION_METHOD_INDEX))
                {
                    if (pButtonControl->doesLocateAt(pCreationPanel->uniqueKey()))
                    {
                        DynamicPanel* pPanel = DynamicZone::get()->getDynamicPanelAt(CREATION_METHOD_INDEX);
                        pPanel->setUserData(DynamicPanelStatus::eCreating);
                        m_manager->SwitchTo(ETemporaryStatus::eCreation);
                    }
                }
            }
        }
    }
}
